package com.testing.login;

import com.testing.mysql.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "GetUserInfo")
public class GetUserInfo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // 设置请求和返回的编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String userinfoResult="{";
        //获取到已经存在session中的用户名
        if(request.getSession().getAttribute("loginUser")==null) {
            userinfoResult+="\"msg\":\"您还没有登录，不能获取用户信息\"}";
        }
        else {
            //已经登录获取了用户名信息的情况下，调用sql语句进行查询，得到返回结果
            String loginName=request.getSession().getAttribute("loginUser").toString();
            if (loginName != null) {
                MysqlUtils mysql = new MysqlUtils();
                mysql.createConnection();
                Map<String, String> userMap = mysql.getUserInfo(loginName);
                //获取到的map中的信息，拼接成为一个json格式。
                for (String key : userMap.keySet()) {
                    //json字符串的格式"键":"值"
                    userinfoResult += "\"" + key + "\":\"" + userMap.get(key) + "\",";
                }
                userinfoResult += "}";
                userinfoResult = userinfoResult.replace(",}", "}");
                System.out.println(userinfoResult);
            } else {
                userinfoResult += "\"msg\":\"您还没有登录，不能获取用户信息\"}";
            }
        }
        response.getWriter().append(userinfoResult);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //后端处理的时候，请求和返回编码都设置为utf-8
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //        设置返回头content-type的格式,以及编码为utf-8
        response.setContentType("text/html;charset=utf-8");
        String result = "{\"msg\":\"不支持使用get方法查询用户信息\",\"code\":\"1\"}";
        response.getWriter().append(result);
    }
}
